package geektime.spring.springbucks.redis;


import com.github.pagehelper.PageInfo;
import com.sun.org.apache.xpath.internal.operations.Bool;
import geektime.spring.springbucks.model.Coffee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j  //日志的处理
public class JedisServiceImpl {

    @Autowired
    private JedisUtils jedisUtils;

    /**
     * 开始时间戳，参考方法getTimesMap()
     */
    private static final long BEGIN_TIMESTAMP = 1645568542L;
    /**
     * 序列号的位数
     */
    private static final int COUNT_BITS = 32;
    /**
     * 自增前缀
     */
    private String keyPrefix = "Order";

    public String  getString(String key){
        Jedis jedis=jedisUtils.getJedis();
        String val=jedis.get(key);
        log.info(key+"是在Redis中查询的数据。值是："+val);
        jedisUtils.close(jedis); //释放资源
        return val;
    }

    public Boolean getBit(String key, Long offset) {
        Jedis jedis=jedisUtils.getJedis();
        boolean result =  jedis.getbit(key,offset);
        log.info(key+"在Redis中"+offset+"查询的数据是否存在："+result);
        jedisUtils.close(jedis); //释放资源
        return result;
    }

    public Boolean setBit(String key, Long offset,boolean bool) {
        Jedis jedis=jedisUtils.getJedis();
        boolean result =  jedis.setbit(key,offset,bool);
        log.info(key+"在Redis中"+offset+"添加数据是否存在");
        jedisUtils.close(jedis); //释放资源
        return result;
    }

      public String  setString(String key,String val){
        Jedis jedis=jedisUtils.getJedis();
       jedis.set(key,val);
       log.info(key+"存入Redis中。值是："+val);
        jedisUtils.close(jedis); //释放资源
        return val;
    }

    // 生成全局唯一ID
    public long nextId() {
        Jedis jedis=jedisUtils.getJedis();
        // 1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        // 2.生成序列号
        // 2.1.获取当前日期，精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 2.2.自增长
        long count = jedis.incr("ID:" + keyPrefix + ":" + date);
        // 3.拼接
        long id = timestamp << COUNT_BITS | count;
        jedisUtils.close(jedis); //释放资源
        return id;
    }
}
